package com.server.server_a10.controller.test;

import com.server.server_a10.entity.User;
import com.server.server_a10.mapper.LoginMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
public class getImg {

    @RequestMapping(value="/file",method = RequestMethod.GET)
    public String up(MultipartFile photo, HttpServletRequest request) {
        if(photo==null){
            return "null的";
        }

        //文件名
        System.out.println(photo.getOriginalFilename());
        //文件类型
        System.out.println(photo.getContentType());

        //服务器的运行目录
        String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\image\\";
        System.out.println(path);

        if(saveFile(photo,path)){
            return "success";
        }
        return "nonono";
    }

    public boolean saveFile(MultipartFile photo, String path){
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }

        //参数为所保存的路径名称，此时为动态路径，也可以是静态的  例如改为d:/
        File file = new File(path+photo.getOriginalFilename());
        System.out.println("path=>"+path+photo.getOriginalFilename());
        try {
            //存储
            photo.transferTo(file);
        } catch (IOException e) {
            return false;
        }
        return true;
    }


    @Autowired
    LoginMapping loginMapping;

    @GetMapping(value = "/getAllUsers")
    public String getAllUsers(){
        List<User> users = loginMapping.selectAllUser();
        System.out.println(users);
        for (User u:users){
            System.out.println(u.toString());
        }
        return users.toString();
    }
}
